<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="curId ? '编辑服务器' : '新增服务器'"
    width="720px"
    :before-close="dialogClose"
  >
    <el-form
      ref="ruleForm"
      :rules="rules"
      :model="ruleForm"
      inline
      label-position="left"
      status-icon
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-card shadow="never">
        <el-form-item label="主机名" prop="hostname">
          <el-input v-model="ruleForm.hostname" clearable />
        </el-form-item>
        <el-form-item label="实例ID" prop="instance_id">
          <el-input v-model="ruleForm.instance_id" clearable />
        </el-form-item>
        <el-form-item label="IP" prop="ip">
          <el-input v-model="ruleForm.ip" clearable />
        </el-form-item>
        <el-form-item label="弹性地址" prop="floatingip">
          <el-input v-model="ruleForm.floatingip" clearable />
        </el-form-item>

        <el-form-item label="平台" prop="">
          <el-select
            v-model="ruleForm.platform_id"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in platformsData"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="">
          <el-select
            v-model="ruleForm.region_id"
            filterable
            clearable
            placeholder="选择区域"
          >
            <el-option
              v-for="item in regionOptions"
              :key="item.id"
              :label="`${item.city}-${item.region}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="主机分组：" prop="group">
          <el-select v-model="ruleForm.group"  multiple>
              <el-option v-for="item in Group" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="SSH账号" prop="ssh_id  ">
          <el-select
            v-model="ruleForm.ssh_id"
            filterable
            clearable
            placeholder="选择账号"
          >
            <el-option
              v-for="item in sshOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="connect_type" label="连接方式: ">
          <el-col :span="1.5">
            <el-tag size="large" type="info">IP</el-tag>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-radio-group v-model="ruleForm.connect_type">
              <el-radio :label="1">公网</el-radio>
              <el-radio :label="2">内网</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
      </el-card>

      <div v-show="dialogDetail">
        <el-divider content-position="left">
          <el-button
            @click="
              serverDetailVisible
                ? (serverDetailVisible = false)
                : (serverDetailVisible = true)
            "
          >
            更多</el-button
          >
        </el-divider>

        <div v-show="serverDetailVisible">
          <el-card shadow="never">
            <el-form-item label="类型" prop="">
              <el-select
                v-model="ruleForm.asset_type"
                clearable
                placeholder="选择服务器类型"
              >
                <el-option
                  v-for="item in serverTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="系统版本" prop="os_version">
              <el-input v-model="ruleForm.os_version" clearable />
            </el-form-item>
            <el-form-item label="CPU" prop="cpu">
              <el-input v-model="ruleForm.cpu" clearable />
            </el-form-item>
            <el-form-item label="内存" prop="memory">
              <el-input v-model="ruleForm.memory" clearable />
            </el-form-item>
            <el-form-item label="磁盘" prop="disk">
              <el-input v-model="ruleForm.disk" clearable />
            </el-form-item>

            <el-form-item label="状态" prop="">
              <el-select
                v-model="ruleForm.status"
                clearable
                placeholder="选择服务器状态"
              >
                <el-option
                  v-for="item in ServerStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="desc">
              <el-input v-model="ruleForm.desc" clearable />
            </el-form-item>

            <el-form-item label="租约时间：" prop="expire_time">
              <el-date-picker
                v-model="ruleForm.expire_time"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-card>
        </div>
      </div>

      <div class="el-sub-button">
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
<script>
import {
  createServer,
  updateServer,
  getServer,
  getServerStatus,
  getServerType,
} from "@/api/asset/servers";
import { getsshs } from "@/api/asset/ssh";
import { getRegions } from "@/api/cloudPlatform/region";
import { getPlatforms } from "@/api/cloudPlatform/platform";
// import { validateIP } from "@/utils/rulesValidate";

export default {
  name: "CuForm",
  props: {
    dialogVisible: {
     visible: Boolean,
       default: false,
    },
    dialogDetail: {
      type: Boolean,
      default: false,
    },
    curId: {
      type: Number,
      default: null,
    },
  },
  data() {
    var validateName = (ruleForm, value, callback) => {
      if (!this.ruleForm.ip && !this.ruleForm.floatingip) {
        callback(new Error("请至少填一个连接地址"));
      } else {
        //任意值被填写，清除验证提示
        if (!this.ruleForm.ip || !this.ruleForm.floatingip) {
          this.$refs["ruleForm"].clearValidate(["ip"]);
          this.$refs["ruleForm"].clearValidate(["floatingip"]);
        }
        callback();
      }
    };
    return {
      ruleForm: {
        instance_id: "",
        status: 0,
        region_id: "",
        group_id: [],
        asset_type: "cloud_host",
        connect_type: 1,
      },

      serverDetailVisible: false, // 更多详情展示与隐藏
      ServerStatus: [],
      adminOptions: [],
      platformsData: [],
      sshOptions: [],
      serverTypeOptions: [],
      regionOptions: [],
      groupOptions: [],
      serverSystemOptions: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      rules: {
        ip: [
          {
            required: true,
            validator: validateName,
            trigger: "change",
          },
        ],
        floatingip: [
          {
            required: true,
            validator: validateName,
            trigger: "change",
          },
        ],
        hostname: [
          { required: true, trigger: "blur", message: "服务器名不能为空" },
        ],
        // ip: [
        //   { required: true, trigger: "blur", message: "IP地址不能为空" },
        //   { validator: validateIP, trigger: "blur" },
        // ],
        status: [
          { required: true, trigger: "blur", message: "服务器状态不能为空" },
        ],
      },
    };
  },
  watch: {
    dialogVisible(v) {
      console.log("-------------子组件---------------");
      if (v) {
        if (this.curId) {
          console.log("传入cuId:", this.curId);
          getServer(this.curId).then((response) => {
            // 根据传入的id获取详情页数据
            this.ruleForm = response.data;
            // 从对象中提取ID字段重新赋值
            this.ruleForm.region_id = this.ruleForm.region_id.id;
            this.ruleForm.ssh_id = this.ruleForm.ssh_id.id;
            this.ruleForm.platform_id = this.ruleForm.platform_id.id;
            this.ruleForm.platform_account_id = this.ruleForm.platform_account_id.id;

            const group_id = [];
            for (let i in this.ruleForm.group_id) {
              group_id.push(this.ruleForm.group_id[i].id);
            }
            this.ruleForm.group_id = group_id;

            console.log("打印编辑框已有数据:", response.data);
            console.log("获取选项栏对象id:", this.ruleForm.region_id);
          });
        }

        // 准备下拉栏数据
        this.getServerType();
        this.getServerStatus();
        this.getsshs();
        this.getRegions();
        this.getPlatforms();
      }
    },
  },
  methods: {
    dialogClose() {
      this.serverDetailVisible = false;
      this.ruleForm.group_id = "";
      this.ruleForm.region_id = "";
      this.ruleForm.ssh_id = "";
      this.$refs.ruleForm.resetFields();
      console.log("子组件窗口数据已清理,通知父组件");
      this.$emit("close");
    },
    search() {
      this.dialogClose();
      this.$emit("search");
    },
    getServerType() {
      getServerType().then((res) => {
        this.serverTypeOptions = res.data.results;
      });
    },
    getServerStatus() {
      getServerStatus().then((res) => {
        this.ServerStatus = res.data.results;
      });
    },
    // 查询凭证
    getsshs() {
      getsshs().then((response) => {
        this.sshOptions = response.data.results;
        const passwd = [];
        for (let i in this.sshOptions) {
          passwd.push(
            this.sshOptions[i].name +
              "-" +
              this.sshOptions[i].authentication_type
          );
        }
        console.log("passwd 获取凭证:", passwd);
        console.log("sshOptions", this.sshOptions);
      });
    },
    // 查询平台
    getPlatforms() {
      getPlatforms().then((response) => {
        this.platformsData = response.data.results;
        const platforms = [];
        for (let i in this.platformsData) {
          platforms.push(this.platformsData[i].name);
        }
        console.log("platforms 获取平台:", platforms);
      });
    },

    // 查询区域
    getRegions() {
      getRegions().then((res) => {
        this.regionOptions = res.data.results;
        const regions = [];
        for (let i in this.regionOptions) {
          regions.push(
            this.regionOptions[i].city + "." + this.regionOptions[i].region
          );
          //   console.log("regionsId:", i)
        }
        console.log("regions 获取区域:", regions);
      });
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.curId) {
            // if (!this.ruleForm.department) {
            //   this.ruleForm.department = null
            // }
            updateServer(this.curId, this.ruleForm).then((res) => {
                res
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.search();
            });
          } else {
            createServer(this.ruleForm).then((res) => {
                res
              this.$message({
                message: "新增成功",
                type: "success",
              });

              this.search();
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }

        console.log("ruleForm", this.ruleForm);
      });
    },
    resetForm(formName) {
      if (this.curId) {
        getServer(this.curId).then((res) => {
          this.ruleForm = res.data;
          // 从对象中提取ID字段重新赋值
          this.ruleForm.region_id = this.ruleForm.region_id.id;
          this.ruleForm.ssh_id = this.ruleForm.ssh_id.id;
          this.ruleForm.platform_id = this.ruleForm.platform_id.id;
        });
      } else {
        this.$refs[formName].resetFields();
        this.ruleForm.region_id = "";
        this.ruleForm.ssh_id = "";
        this.ruleForm.platform_id = "";
        this.ruleForm.platform_account_id= "";
      }
    },
  },
};
</script>
<style lang="less" scoped>
.demo-ruleForm ::v-deep .el-card__body {
  padding: 10px 10px 0 10px;
}
.demo-ruleForm ::v-deep .el-card {
  margin-bottom: 10px;
}
.el-sub-button {
  margin-left: 75%;
}
</style>